package com.zhangwei.day41photo.fragment;


import android.database.DataSetObserver;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.zhangwei.day41photo.R;
import com.zhangwei.day41photo.adapter.UPdateImageAdapter;
import com.zhangwei.day41photo.bean.UpdateInfo;
import com.zhangwei.day41photo.utils.FileUtils;
import com.zhangwei.day41photo.utils.ImageUtils;

import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ViewById;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 内存泄露
 * 内存溢出
 * 一功能多图片上传
 * 图片来源 - 拍照 相册
 * 1>拍照指定图片的存储路径
 * 2>显示图片 必须开异步任务去遍历图片保存路径   图片二次采样  BitmapFractory.Option
 * 3>选择图片
 * 4>图片质量压缩
 *
 */
@EFragment(R.layout.fragment_update_images)
public class UpdateImagesFragment extends BaseFragment implements AdapterView.OnItemClickListener {
    public static final String UPDATA_URL = "http://10.6.156.7:8080/app/uplaodFile/upload";


    @ViewById
    GridView updateImgGv;
    @ViewById
    Button updateBtn;


    private UPdateImageAdapter adapter;
    private ArrayList<UpdateInfo> infos = new ArrayList<>();

    @Override
    public void initView() {
        adapter = new UPdateImageAdapter(activity, infos);
        updateImgGv.setOnItemClickListener(this);
        updateImgGv.setAdapter(adapter);
    }

    /**
     * 问题一   不能在主线程中做耗时的操作,否则会导致黑屏现象
     * 问题二   图片内存溢出的问题
     * 图片压缩
     */
    @Override
    public void initData() {

        new AsyncTask<Void, Void, List<UpdateInfo>>() {
            @Override
            protected List<UpdateInfo> doInBackground(Void... params) {
                ArrayList<UpdateInfo> updateInfos = null;
                File photoFile = FileUtils.getPhotoCache(activity);
                File[] files = photoFile.listFiles();
                if (files != null && files.length > 0) {
                    updateInfos = new ArrayList<>();
                    for (File file : files) {
                        Bitmap bitmap = ImageUtils.compressBitmap(file.getAbsolutePath(), 400, 400);
                        updateInfos.add(new UpdateInfo(bitmap, file, false));
                    }
                }
                return updateInfos;
            }

            @Override
            protected void onPostExecute(List<UpdateInfo> updateInfos) {
                super.onPostExecute(updateInfos);
                if (updateInfos != null) {
                    infos.addAll(updateInfos);
                    adapter.notifyDataSetChanged();
                }

            }
        }.execute();
    }

    /**
     * 文件上传
     * Form表单形式上传文件
     */
    public void updateFile() {
//        文件上传上传的功能
        HttpUtils httpUtils = new HttpUtils();
        RequestParams params = new RequestParams();
        for (int i = 0; i < infos.size(); i++) {
            UpdateInfo info = infos.get(i);
            if (info.isCheck()) {
                File file = ImageUtils.compressBmpToFile(info.getBitmap(),info.getFile());
                params.addBodyParameter("file" + i, file);
            }
        }
        httpUtils.send(HttpRequest.HttpMethod.POST, UPDATA_URL, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Log.e("onSuccess", responseInfo.result);
            }

            @Override
            public void onFailure(HttpException error, String msg) {
            }
        });


        adapter.registerDataSetObserver(new DataSetObserver() {
            @Override
            public void onChanged() {
                super.onChanged();
            }

            @Override
            public void onInvalidated() {
                super.onInvalidated();
            }
        });
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        UPdateImageAdapter.ViewHolder vh = (UPdateImageAdapter.ViewHolder) view.getTag();
        UpdateInfo info = infos.get(position);
        if (info.isCheck()) {
            vh.checkBox.setChecked(false);
            info.setIsCheck(false);
        } else {
            vh.checkBox.setChecked(true);
            info.setIsCheck(true);
        }
    }

    @Click(R.id.update_btn)
    public void onClick() {
        updateFile();
    }

}
